<template>
  <PageWrapper title="角色列表" contentFullHeight>
    <!-- 列表 -->
    <div class="py-4">
      <BasicTable
        @register="registerTable"
        :dataSource="state.roleList"
        :loading="state.listLoading"
      >
        <template #toolbar>
          <a-button type="primary" @click="openModal('add')">添加角色</a-button>
        </template>
        <template #expandedRowRender="{ record }">
          <div v-if="record.personAuth.length">
            <div v-for="item in record.personAuth" :key="item.id">
              <polylineTree :rowId="record.id" :rowItem="item" @update-role-auth="updateRoleAuth" />
            </div>
          </div>
          <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
        </template>
        <template #operations="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '编辑',
                icon: 'ant-design:edit-outlined',
                onClick: handleEdit.bind(null, record),
                // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
              },
              {
                label: '删除',
                icon: 'ic:outline-delete-outline',
                // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                popConfirm: {
                  title: '是否删除？',
                  confirm: handleDelete.bind(null, record),
                },
              },
              {
                label: '分配权限',
                icon: 'ant-design:setting-outlined',
                onClick: handleEditRole.bind(null, record),
                // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>

    <!-- 角色弹窗 -->
    <BasicModal
      :title="!state.editStatus ? '添加角色' : '编辑角色'"
      :helpMessage="[`${!state.editStatus ? 'add role' : 'edit role'}`]"
      width="700px"
      @register="register"
      @ok="handleOk"
    >
      <a-form
        ref="userForm"
        class="form-middle"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="角色名称" name="roleName">
          <a-input v-model:value="formState.roleName" />
        </a-form-item>
        <a-form-item label="角色描述" name="roleDesc">
          <a-input v-model:value="formState.roleDesc" />
        </a-form-item>
      </a-form>
    </BasicModal>

    <!-- 权限弹窗 -->
    <BasicModal
      title="分配权限"
      helpMessage="Assign permissions"
      width="700px"
      @register="authRegister"
      @ok="handleAuthOk"
    >
      <a-tree
        checkable
        defaultExpandAll
        :tree-data="shopRoleStore.authData"
        v-model:checkedKeys="state.checkedKeys"
        @check="handleCheck"
      />
    </BasicModal>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, onMounted, UnwrapRef, ref, toRaw, nextTick } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, BasicColumn, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useShopRoleStore } from '/@/store/modules/shopRoleStore';
  import { message } from 'ant-design-vue';
  import polylineTree from './components/polylineTree.vue';
  import { Empty } from 'ant-design-vue';
  import { breadthFirstSearch, depthFirstSearch } from '/@/utils/common';

  interface stateModel {
    columns: BasicColumn[];
    roleList: object[];
    listLoading: boolean;
    editStatus: boolean;
    rowId: number;
    checkedKeys: number[];
    ridsList: number[];
  }

  interface formModel {
    roleName: String;
    roleDesc: String;
  }

  const state: stateModel = reactive({
    columns: [
      {
        title: 'ID',
        dataIndex: 'id',
        width: 200,
      },
      {
        title: '角色名称',
        dataIndex: 'roleName',
      },
      {
        title: '角色描述',
        dataIndex: 'roleDesc',
      },
    ],
    roleList: [],
    listLoading: false,
    editStatus: false,
    rowId: 0,
    checkedKeys: [],
    ridsList: [],
  });

  const formState: UnwrapRef<formModel> = reactive({
    roleName: '',
    roleDesc: '',
  });

  const rules = {
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  };

  const userForm = ref();

  const [registerTable] = useTable({
    title: '角色列表',
    titleHelpMessage: 'roles',
    rowKey: (record: any) => {
      return record.roleName;
    },
    columns: state.columns,
    striped: true,
    bordered: true,
    showTableSetting: false,
    expandRowByClick: true,
    actionColumn: {
      title: '操作',
      dataIndex: 'operations',
      slots: { customRender: 'operations' },
    },
  });

  const [register, { setModalProps, closeModal, changeOkLoading }] = useModalInner();
  const [authRegister, authFn] = useModalInner();

  const shopRoleStore = useShopRoleStore();

  onMounted(() => {
    getRoleList();
  });

  const getRoleList = async () => {
    state.listLoading = true;
    try {
      const res = await shopRoleStore.roleList();
      shopRoleStore.authList({ type: 'tree' });
      state.roleList = res;
    } catch (error) {
      console.error(error);
    }
    state.listLoading = false;
  };
  const handleAdd = async () => {
    try {
      const res = await userForm.value.validate();
      await shopRoleStore.addRole(res);
      message.success('创建成功');
      closeModal();
      userForm.value.resetFields();
      getRoleList();
    } catch (error) {
      console.log(error);
    }
  };
  const handleEdit = async (record: any) => {
    const { id } = record;
    state.rowId = id;
    openModal('edit');
    try {
      const res = await shopRoleStore.singleRole({ id: state.rowId });
      formState.roleName = res.roleName;
      formState.roleDesc = res.roleDesc;
    } catch (error) {
      console.log(error);
    }
  };
  const submitEditRole = async () => {
    const toRawFormState: any = toRaw(formState);
    try {
      await shopRoleStore.submitSingleRole({ id: state.rowId, ...toRawFormState });
      message.success('修改成功');
      closeModal();
      getRoleList();
    } catch (error) {
      console.log(error);
    }
  };
  const handleDelete = async (record: any) => {
    try {
      const { id } = record;
      await shopRoleStore.deleteRole({ id });
      message.success('删除成功');
      getRoleList();
    } catch (error) {
      console.log(error);
    }
  };
  const openModal = async (type?: string) => {
    if (type === 'add') {
      state.editStatus = false;
    }
    if (type === 'edit') {
      state.editStatus = true;
    }
    setModalProps({ visible: true });
    await nextTick();
    userForm.value.resetFields();
  };
  const handleOk = async () => {
    changeOkLoading(true);
    if (state.editStatus) {
      submitEditRole();
    } else {
      handleAdd();
    }
    changeOkLoading(false);
  };
  const handleEditRole = async (record: any) => {
    state.checkedKeys = [];
    state.ridsList = [];
    state.rowId = record.id;
    breadthFirstSearch(record.personAuth, (node) => {
      state.checkedKeys.push(node.id);
    });
    depthFirstSearch(record.personAuth, (item) => {
      state.ridsList.push(item.id);
    });
    authFn.setModalProps({ visible: true });
  };
  const handleAuthOk = async () => {
    authFn.changeOkLoading(true);
    try {
      await shopRoleStore.addRoleAuth({ roleId: state.rowId, rids: state.ridsList.join(',') });
      message.success('更新成功');
      authFn.setModalProps({ visible: false });
      getRoleList();
    } catch (error) {
      console.error(error);
    }
    authFn.changeOkLoading(false);
  };
  const handleCheck = (checkedKeys: number[], e: any) => {
    state.ridsList = [...checkedKeys, ...e.halfCheckedKeys];
  };
  const updateRoleAuth = (data: any) => {
    state.roleList.forEach((item: any) => {
      if (item.id === data[0]) {
        item.personAuth = data[1];
      }
    });
  };
</script>
